package com.nuoniu.sibanyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.DateUtils;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.*;
import com.nuoniu.sibanyun.entity.bo.SysUserDataScopeBo;
import com.nuoniu.sibanyun.entity.crm.*;
import com.nuoniu.sibanyun.entity.dto.SysUserDto;
import com.nuoniu.sibanyun.entity.project.SysRdtForm;
import com.nuoniu.sibanyun.entity.vo.*;
import com.nuoniu.sibanyun.mapper.*;
import com.nuoniu.sibanyun.mapper.crm.CrmCustomerMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmDefineFieldMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmStrategyMapper;
import com.nuoniu.sibanyun.mapper.erp.ErpNumberSetMapper;
import com.nuoniu.sibanyun.mapper.project.SysRdtFormMapper;
import com.nuoniu.sibanyun.service.*;
import com.nuoniu.sibanyun.service.crm.*;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.expenses.IExpensesAccountService;
import com.nuoniu.sibanyun.service.redis.RedisService;
import com.nuoniu.sibanyun.userThread.DataScope;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.ExcelUtils;
import com.nuoniu.sibanyun.utils.HttpClientUtil;
import com.nuoniu.sibanyun.utils.IpUtil;
import com.nuoniu.sibanyun.utils.SendSmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-04-23
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private ISysMenuService sysMenuService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysEmployeeMapper employeeMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private SysCompanyMapper companyMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private SendSmsMapper sendSmsMapper;
    @Autowired
    private SysOfficeMapper officeMapper;
    @Autowired
    private CrmDefineFieldMapper fieldMapper;
    @Autowired
    private CrmStrategyMapper strategyMapper;
    @Autowired
    private ErpNumberSetMapper numberSetMapper;
    @Autowired
    private ISysRoleDataScopeService sysRoleDataScopeService;
    @Autowired
    private ICrmWebConfigService configService;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private ICrmLinkmanService linkmanService;
    @Autowired
    private ICrmGoodsService crmGoodsService;
    @Autowired
    private IExpensesAccountService expensesAccountService;
    @Autowired
    private ICrmUserLevelService userLevelService;
    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private ICrmRetailLevelService levelService;
    @Autowired
    private SysRdtFormMapper formMapper;
    @Autowired
    private CrmCustomerMapper crmMapper;
    @Autowired
    private SysCompanyServiceImpl companyService;

    public static String SignName = "四班云";
    //zy新增
    @Override
    public SysUser getByUserId(Long id) {
        return baseMapper.getByUser(id);
    }
    //zy新增
    @Override
    public Page<SysEmployeeSimpleVo> pageSysEmployeeSimpleVo(Page page, Integer officeId, String searchKey) {
        UserInfo userInfo = UserThreadLocal.get();
//        if (null == officeId) throw new NuoNiuException("请选择部门");
        Page<SysEmployeeSimpleVo> sysEmployeeSimpleVoPage = baseMapper.pageSysEmployeeSimpleVo(page, userInfo.getCompanyId(), officeId,searchKey);
        return sysEmployeeSimpleVoPage;
    }
    //zy新增
    @Override
    public Map importEmployee(MultipartFile file) throws IOException, NoSuchFieldException {
        return null;
    }
//zy新增
    @Override
    public Page<SysUser> pageList(Page page) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        return page(page, wrapper);
    }
    //zy新增
    @Override
    public void importTemplate(HttpServletResponse response) {
        String fileName = "导入员工模板.xls";
        String[] data = {"001", "小明", "13320371111", "xm", "汉族", "xx@qq.com", "重庆市江北区"};
        Object[] title = {"员工工号", "员工姓名", "手机号", "英文名", "民族", "邮箱", "居住地址"};
        ExcelUtils.export(title,  fileName, data, response);
    }
    //zy新增
    @Override
    public void inviteToRegister(String[] userPhones) {
        List<String> signNameList = new ArrayList<>();
        List<Map<String, String>> paramList = new ArrayList<>();
        UserInfo userInfo = UserThreadLocal.get();
        SysCompany company = companyService.getById(userInfo.getCompanyId());
        if(company != null) {
            for(String userPhone : userPhones) {
                SysUser sysUser = baseMapper.getByUserPhone(userPhone);
                if(sysUser != null && sysUser.getId() == null) {
                    Map<String, String> param = new HashMap<>();
                    signNameList.add(SignName);
                    param.put("code", sysUser.getId().toString());
                    paramList.add(param);
                }
            }

            if(signNameList.size() > 0) {
                SendSmsUtils.sendEmpSms(JSON.toJSONString(signNameList), JSON.toJSONString(paramList), JSON.toJSONString(userPhones));
            }
        }
    }
//zy新增
    @Override
    public void deletebyid(Long id) {
        SysUser sysUser = getById(id);
        if(sysUser != null && sysUser.getId() != null) {
            throw new NuoNiuException("已入职,不能删除");
        }
        this.baseMapper.deleteByUserId(id.intValue());
    }
//*******************************************************

    @Override
    public List<String> listRolesString(String userName) {
        return baseMapper.listRolesString(userName);
    }

    @Override
    public List<String> listPermissionsString(String userName) {
        return baseMapper.listPermissionsString(userName);
    }

    @Override
    public SysUser findByUserName(String userName) {
        return baseMapper.findByUserName(userName);
    }

    @Override
    public SysUser findByToken(HttpServletRequest request) {
        UserInfo userInfo = UserThreadLocal.get();
        SysUser byUserName =  baseMapper.findByUserName(userInfo.getUserName());
        return byUserName;
    }

    @Override
    public UserSimpleVo getUserSimpleVo(HttpServletRequest request) {
        UserInfo userInfo = UserThreadLocal.get();
        UserSimpleVo result = new UserSimpleVo();
        SysUser currentUser = getById(userInfo.getUserId());
        List<SysRole> sysRoles = sysRoleService.listByUserId(Long.valueOf(userInfo.getUserId()));
        List<SysMenu> sysMenus = sysMenuService.listByUserId(Long.valueOf(userInfo.getUserId()));
        /** 获取公司管理员角色ID */
        Integer adminRoleId = crmGoodsService.getCompanySysRoleIdByCompanyId();
        //（权限二次过滤，避免数据异常导致的权限溢出）租户下的所有用户 不能超出 租户管理员的权限（包括租户管理员自己也过滤了）
        if( 1 != userInfo.getUserId()){
            //获取 系统管理员角色的 菜单ID
            List<Long> adminRoleMenuIds = sysMenuService.getMenuIdsByRoleId(adminRoleId);
            sysMenus = sysMenus.stream().filter(menu->adminRoleMenuIds.contains(menu.getId())).collect(Collectors.toList());
        }
        result.setId(currentUser.getId());
        result.setName(currentUser.getRealName());
        result.setAvatar(currentUser.getAvatar());
        result.setCompanyId(currentUser.getCompanyId());
        result.setCompanyName(currentUser.getCompanyName());

        result.setRoles(sysRoles.stream().filter(f-> StringUtils.isNotBlank(f.getRoleName())).map(SysRole::getRoleName).collect(Collectors.toSet()));
        if(userInfo.getStatus() == 0){
            result.setPermissions(sysMenus.stream().filter(f-> StringUtils.isNotBlank(f.getPermission())).map(SysMenu::getPermission).collect(Collectors.toSet()));
        }
        Set<String> permissions = result.getPermissions();
        if("system".equals(userInfo.getUserName())){
            permissions.add("NuoNiu");
        }

        //获取已使用产品
        if(userInfo.getCompanyId() != null) {
            SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
            if(company != null && company.getGoodsId() != null) {
                CrmGoods goods = crmGoodsService.getById(company.getGoodsId());
                result.setGoodsId(goods.getId().intValue());
                result.setGoodsName(goods.getGoodsName());
                result.setGoodsLogoUrl(goods.getGoodsLogoUrl());
            }
        }
        return result;
    }

    @Override
    public UserInfo getUserInfo(String userName) {
        UserInfo userInfo = baseMapper.getUserInfo(userName);
        userInfo.setRoleIds(baseMapper.getUserRoleIds(userInfo.getUserId()));
        DataScope userDataScope = getUserDataScope(userInfo);
        userInfo.setDataScope(userDataScope);
        return userInfo;
    }

    @Override
    public Page<SysUserDto> getUserPage(SysUserDto userDto) {
//    public Page<SysEmployee> getUserPage(SysUserDto userDto) {
        UserInfo userInfo = UserThreadLocal.get();
        if(userDto.getOfficeId() != null) {
            SysOffice office = officeMapper.selectById(userDto.getOfficeId());
            if(office.getParentId() != 0 && StringUtils.isNotBlank(office.getOfficeCode())) {
                userDto.setOfficeCode(office.getOfficeCode());
            }else {
                userDto.setOfficeId(null);
            }
        }

        userDto.setCompanyId(userInfo.getCompanyId().longValue());
        Page<SysUserDto> userDtoPage = userMapper.getUserPage(userDto.getPage(), userDto);

//        Page<SysEmployee> userDtoPage =  employeeMapper.getUserPage(userDto.getPage(), userDto);


        //List<SysUserDto> userDtoList = userDtoPage.getRecords(); //遍历角色
//        for(SysUserDto user : userDtoList) {
//            List<SysRoleDto> roleDtos = userMapper.getUserRole(user.getId());
//            String roleName = "";
//            for(int i=0; i<roleDtos.size(); i++) {
//                if(roleDtos.get(i).getId() == 9) {
//                    user.setIsSysAdmin(true);
//                }
//                roleName += roleDtos.get(i).getRoleName();
//                if(i + 1 < roleDtos.size()) {
//                    roleName += "+";
//                }
//            }
//            user.setRoleName(roleName);
//        }
        return userDtoPage;
    }

    @Override
    public void saveUser(SysUserDto sysUser) {
        UserInfo userInfo = UserThreadLocal.get();
        SysUser user = userMapper.findByUserName(sysUser.getUserName());
        if(user != null && sysUser.getId() == null) {
            throw new NuoNiuException("登录账号已存在");
        }

        List<UserInfo> userInfos = userMapper.getUserList(userInfo.getCompanyId());
        SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
        //保存用户信息
//        user = new SysUser();
        BeanUtils.copyProperties(sysUser, user);
        SysOffice office = officeMapper.selectById(sysUser.getOfficeId());
        if(sysUser.getId() == null) {
            if(company.getCompanyUser() + company.getFreeUser() <= userInfos.size()) {
                user.setStatus(2);
            }

            user.setCompanyId(userInfo.getCompanyId());
            user.setCompanyName(userInfo.getCompanyName());
            user.setCreateBy(userInfo.getUserId());
            user.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            user.setUpdateBy(userInfo.getUserId());
            user.setId(user.getId());
            user.setRealName(user.getRealName());
            user.setOfficeId(sysUser.getOfficeId());
            if(office != null && office.getOfficeCode() != null) {
                user.setOfficeCode(office.getOfficeCode());
            }
            user.setOfficeName(sysUser.getOfficeName());
            save(user);
        }else {
            //修改用户
            user.setUpdateBy(userInfo.getUserId());
            user.setId(sysUser.getId());
            user.setUpdateDate(LocalDateTime.now());
            user.setUpdateBy(userInfo.getUserId());
            user.setRealName(user.getRealName());
            user.setOfficeId(sysUser.getOfficeId());
            user.setOfficeName(sysUser.getOfficeName());
            if(office != null && office.getOfficeCode() != null) {
                user.setOfficeCode(office.getOfficeCode());
            }
            updateById(user);
        }
//zy修改
//        //保存员工
//        SysUser SysUser =  baseMapper.getByUser(user.getId());
//        SysOffice office = officeMapper.selectById(sysUser.getOfficeId());
//        if(SysUser == null) {
//            SysUser = new SysUser();
//            SysUser.setCompanyId(userInfo.getCompanyId().longValue());
//            SysUser.setCompanyName(userInfo.getCompanyName());
//            SysUser.setCreateBy(userInfo.getUserId());
//            SysUser.setUpdateBy(userInfo.getUserId());
//            SysUser.setUserId(user.getId());
//            SysUser.setEmpName(user.getRealName());
//            SysUser.setOfficeId(sysUser.getOfficeId());
//            if(office != null && office.getOfficeCode() != null) {
//                SysUser.setOfficeCode(office.getOfficeCode());
//            }
//            SysUser.setOfficeName(sysUser.getOfficeName());
//            baseMapper.insert(SysUser); //保存员工信息
//        }else {
//            SysUser.setEmpName(user.getRealName());
//            SysUser.setOfficeId(sysUser.getOfficeId());
//            SysUser.setOfficeName(sysUser.getOfficeName());
//            if(office != null && office.getOfficeCode() != null) {
//                SysUser.setOfficeCode(office.getOfficeCode());
//            }
//            baseMapper.updateById(SysUser);
//        }

        //保存用户角色
        SysUserRole sysUserRole = userRoleMapper.getUserAdminRole(user.getId().intValue(), crmGoodsService.getCompanySysRoleIdByCompanyId());
        if(sysUserRole == null) { //系统管理员不更改角色
            userRoleMapper.deleteById(user.getId());
            if(sysUser.getRoleId().size() > 0) {
                for(int i=0; i<sysUser.getRoleId().size(); i++) {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(sysUser.getRoleId().get(i));
                    userRoleMapper.insert(userRole);
                }
            }
        }
    }

    @Override
    public void delete(Long userId) {
        throw new NuoNiuException("不能删除员工");
    }

    @Override
    public void resetPassword(SysUserDto user) {
        if(user != null && user.getUserId() != null) {
            for(int i=0; i<user.getUserId().size(); i ++) {
                SysUser sysUser = new SysUser();
                sysUser.setId(user.getUserId().get(i));
                sysUser.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
                updateById(sysUser);
            }
            return;
        }
        throw new NuoNiuException("重置失败,请选择用户");
    }

    @Override
    public void updateSysManager(Long userId) {
        UserInfo userInfo = UserThreadLocal.get();
        SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
        if(!company.getId().equals(1) && company.getGoodsId() != null) {
            CrmGoods goods = crmGoodsService.getById(company.getGoodsId());
            SysUser user = userMapper.getSysManager(userInfo.getCompanyId(), goods.getRoleId());
            if(user.getId().equals(userId)) {
                throw new NuoNiuException("该账号已是系统管理员！");
            }

            SysUser sysUser = this.getById(userId);
            if(sysUser.getStatus() == 0) { //停用用户不能设为管理员
                if(user != null) {
                    SysUserRole userRole = new SysUserRole();
                    //删除旧管理员
                    userRoleMapper.deleteById(user.getId());
                    //保存新管理员
                    userRoleMapper.deleteById(userId);
                    userRole.setRoleId(goods.getRoleId().longValue());
                    userRole.setUserId(userId);
                    userRoleMapper.insert(userRole);
                }else {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setRoleId(goods.getRoleId().longValue());
                    userRole.setUserId(userId);
                    userRoleMapper.insert(userRole);
                }
            }
        } else {
            throw new NuoNiuException("请先选择产品(系统管理->系统信息->产品)");
        }
    }

    @Override
    public void saveUserRole(List<Long> roleIds, Long userId) {
        Integer roleId = 9;
        Integer sysRoleIdByCompanyId = crmGoodsService.getCompanySysRoleIdByCompanyId();
        if(sysRoleIdByCompanyId != null ) {
            roleId = sysRoleIdByCompanyId;
        }

        SysUserRole sysUserRole = userRoleMapper.getUserAdminRole(userId.intValue(), roleId);
        if(sysUserRole != null) {
            throw new NuoNiuException("系统管理员不能更换角色");
        }

        //保存用户角色
        userRoleMapper.deleteByUserId(userId);
        if(roleIds.size() > 0) {
            for(int i=0; i<roleIds.size(); i++) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleIds.get(i));
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    @Transactional
    public HttpResult registerUser(Map<String, String> registerUser) {
        String userPhone = registerUser.get("userPhone");
        String email = registerUser.get("email");
        Object smsCode = redisService.get("sms_" + userPhone);
        if(smsCode == null || !registerUser.get("vCode").equals(smsCode.toString())) {
            throw new NuoNiuException("验证码不正确");
        }

        SysUser user = userMapper.findByUserName(userPhone);
        if(user != null) {
            throw new NuoNiuException("手机号已注册");
        }

        SysUser user1 = userMapper.findByEmail(email);
        if(user1 != null) {
            throw new NuoNiuException("邮箱已注册");
        }

        if(redisService.hasKey("register_" + userPhone)) {
            throw new NuoNiuException("正在注册中...");
        }

        redisService.set("register_" + userPhone, "用户注册", 10);
        String shareCode = registerUser.get("shareCode");
        String sharePhone = registerUser.get("sharePhone");
        SysUser shareUser = userMapper.getShareUser(shareCode, sharePhone); //获取推荐人信息

        user = new SysUser();
        user.setUserCode(com.nuoniu.sibanyun.common.lang.StringUtils.getRandomStr(6));
        user.setPassword(bCryptPasswordEncoder.encode(registerUser.get("password")));
        user.setRegisterIp(IpUtil.getClientIp(request));
        user.setMobile(userPhone);
        user.setUserName(userPhone);
        user.setRealName(registerUser.get("realName"));
        user.setEmail(email);
        user.setTotalCommission(new BigDecimal(0));
        user.setWithdrawalCommission(new BigDecimal(0));
        user.setRegisterAddress(userLocation());

        if(shareUser != null) {
            user.setShareUserId(shareUser.getId().intValue());
            user.setShareUserName(shareUser.getRealName());
            if(StringUtils.isNotBlank(shareUser.getShareUserIds())) {
                String[] ids = shareUser.getShareUserIds().split(",");
                if(ids.length < 4) {
                    user.setShareUserIds(shareUser.getId() + "," + shareUser.getShareUserIds());
                }else {
                    user.setShareUserIds(shareUser.getId() + "," + ids[0] + "," + ids[1] + "," + ids[2]);
                }
            }else {
                user.setShareUserIds(shareUser.getId().toString());
            }

            Integer year = Integer.valueOf(DateUtils.getYear());
            Integer month = Integer.valueOf(DateUtils.getMonth());
            CrmUserLevel userLevel = userLevelService.getByUserId(shareUser.getId().intValue(), year, month);
            if(userLevel == null) {
                CrmRetailLevel level = levelService.getById(1);
                userLevel = new CrmUserLevel();
                userLevel.setYear(year);
                userLevel.setMonth(month);
                userLevel.setUserId(shareUser.getId().intValue());
                userLevel.setName(level.getName());
                userLevel.setDirectCommission(level.getDirectCommission());
            }

            userLevel.setInviteCount(userLevel.getInviteCount() + 1);
            if(registerUser.get("userType").equals("1")) {
                userLevel.setCrmCount(userLevel.getCrmCount() + 1);
            }
            userLevelService.saveLevel(userLevel);
        }

        //单位注册
        if(registerUser.get("userType").equals("1")) {
            String companyName = registerUser.get("companyName");
            CrmWebConfig webConfig = configService.getById(1);
            SysCompany sysCompany = companyMapper.getByName(companyName);
            if(sysCompany != null) {
               throw new NuoNiuException("单位名称已注册");
            }

            sysCompany = new SysCompany();
            sysCompany.setCompanyCode(com.nuoniu.sibanyun.common.lang.StringUtils.getRandomStr(6));
            sysCompany.setCompanyName(companyName);
            sysCompany.setFullName(companyName);
            sysCompany.setRegisterIp(IpUtil.getClientIp(request));
            sysCompany.setFreeUser(webConfig.getFreeUsers());
            sysCompany.setCreateBy(user.getRealName());
            sysCompany.setMobile(userPhone);
            if(shareUser != null) {
                sysCompany.setShareUserId(shareUser.getId().intValue());
                sysCompany.setShareUserName(shareUser.getRealName());
                sysCompany.setType("邀请码注册");
            }

            sysCompany.setRegisterAddress(userLocation());
            companyMapper.insert(sysCompany);
            //添加到诺牛科技客户下
            SysCompany company = companyMapper.selectById(88);
            if(company != null) {
                CrmCustomer crm = new CrmCustomer();
                crm.setCrmName(companyName);
                crm.setCrmType(0);
                crm.setCrmNo(crmCustomerService.getCustomerNo(88));
                crm.setCrmSource("注册");
                crm.setType("客户");
                crm.setCompanyId(88);
                crm.setIsCustomer(true);
                crm.setCompanyName(company.getCompanyName());
                crm.setPhone(userPhone);
                crm.setEmail(email);
                crmCustomerService.save(crm);

                //添加联系人
                CrmLinkman linkman = new CrmLinkman();
                linkman.setCompanyId(88);
                linkman.setCrmId(crm.getId().intValue());
                linkman.setCrmName(crm.getCrmName());
                linkman.setName(user.getRealName());
                linkman.setMobile(userPhone);
                linkman.setEmail(email);
                linkmanService.save(linkman);
            }

            //增加默认部门
            SysOffice office = new SysOffice();
            office.setCompanyId(sysCompany.getId().intValue());
            office.setCompanyName(companyName);
            office.setParentId(0);
            office.setParentIds("0,");
            office.setTreeNames(companyName);
            office.setOfficeName(companyName);
            office.setFullName(companyName);
            office.setOfficeType(1);
            office.setTreeSort(0);
            officeMapper.insert(office);

            //保存用户
            user.setCompanyId(sysCompany.getId().intValue());
            user.setCompanyName(sysCompany.getCompanyName());
            user.setUserType(registerUser.get("userType"));
            user.setCompanyId(sysCompany.getId().intValue());
            user.setCompanyName(companyName);
            user.setId(user.getId());
            user.setRealName(user.getRealName());
            user.setMobile(userPhone);
            user.setOfficeName(companyName);
            user.setOfficeId(office.getId());
            save(user);




            //默认管理员角色
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(2L);
            userRole.setUserId(user.getId());
            userRoleMapper.insert(userRole);

            //异步copy系统字段、系统设置、客户设置
            saveCrmSysField(sysCompany.getId(), sysCompany.getCompanyName(), user.getId(), user.getRealName());
        }else { //个人注册
            save(user);
            //默认个人角色
//            SysUserRole userRole = new SysUserRole();
//            userRole.setUserId(user.getId());
//            userRole.setRoleId(22l);
//            userRoleMapper.insert(userRole);
        }

        return HttpResult.ok("注册成功，请登录");
    }

    @Async
    public void saveCrmSysField(Long companyId, String companyName, Long userId, String realName) {
        //字段设置
        fieldMapper.saveAll(companyId, companyName, userId, realName);
        //客户策略
        strategyMapper.saveAll(companyId, companyName, userId, realName);
        //编码
        numberSetMapper.initCrmCode(companyId.intValue(), companyName, userId.intValue(), realName);
        /** 初始化余额账户*/
        expensesAccountService.initExpensesAccount(companyId.intValue());
        //初始化账套/期间/科目
        accountService.initErpAccount(companyId, companyName);



        //默认角色
//        SysRole sysRole = sysRoleService.getById(107);
//        if(sysRole != null) {
//            sysRole.setCompanyId(companyId.intValue());
//            sysRole.setCompanyName(companyName);
//            sysRole.setId(null);
//            sysRole.setRoleName("默认角色");
//            sysRoleService.save(sysRole);
//            //默认角色菜单
//            roleMenuMapper.saveALl(sysRole.getId());
//        }
    }

    @Override
    public String sendUserCode(String userPhone, String remarks) {
        Map<String, Object> data = SendSmsUtils.sentSms(userPhone);
        String result = data.get("result").toString();
        if ("success".equals(result)) {
            redisService.set("check_" + userPhone, "1", 60);
            String code = data.get("code").toString();
            //验证码保存到redis中
            redisService.set("sms_" + userPhone, code, 900);
            //保存发送记录
            SendSms sendSms = new SendSms();
            sendSms.setPhone(userPhone);
            sendSms.setCode(code);
            sendSms.setType(1);
            sendSms.setRemarks(remarks);
            sendSms.setIp(IpUtil.getClientIp(request));
            sendSmsMapper.insert(sendSms);
        } else {
            throw new NuoNiuException("发送失败");
        }
        return "发送成功！";
    }

    @Override
    public HttpResult checkUser(String userPhone, String userName, String email, String companyName) {
        if(StringUtils.isNotEmpty(userPhone)) {
            String regex = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(userPhone);
            boolean isMatch = m.matches();
            if(!isMatch) {
                throw new NuoNiuException("手机号格式不正确");
            }

            SysUser user = userMapper.findByUserName(userPhone);
            if(user != null) {
                throw new NuoNiuException("手机号已注册");
            }
        }

        if(StringUtils.isNotEmpty(companyName)) {
            SysCompany company = companyMapper.getByName(companyName);
            if(company != null) {
                throw new NuoNiuException("公司已存在");
            }
        }

        if(StringUtils.isNotBlank(email)) {
            SysUser user = userMapper.findByEmail(email);
            if(user != null) {
                throw new NuoNiuException("邮箱已注册");
            }
        }
        return HttpResult.ok();
    }

    @Override
    public SysUser getUserByPhone(String userPhone) {
        return userMapper.findByUserName(userPhone);
    }

    @Override
    public DataScope getUserDataScope(UserInfo userInfo) {
        DataScope dataScope = new DataScope();
        //a.最低 个人权限
        dataScope.setType(1);
        dataScope.setCompanyId(userInfo.getCompanyId());
        //获取 用户数据权限
        List<SysRole> sysRoles = sysRoleService.listByUserId(Long.valueOf(userInfo.getUserId()));
        //1.获取最大角色类型权限
        Set<Integer> dataScopeSet = sysRoles.stream().map(SysRole::getDataScope).collect(Collectors.toSet());
        if( 0 != dataScopeSet.size() ){
            Integer max = Collections.max(dataScopeSet);
            //c.其他权限 非个人权限
            dataScope.setType(max);
        }else{
            dataScope.setType(1);
        }
        //b.如果有公司权限 理解返回
        if( dataScopeSet.contains(3)){
            dataScope.setType(3);
            return dataScope;
        }

        //2.获取具体 数据权限
        Set<Long> sysRoleIdSet = sysRoles.stream().map(f -> f.getId()).collect(Collectors.toSet());
        Set<String> userSet = new HashSet<>();
        Set<String> officeSet =  new HashSet<>();
        List<SysUserDataScopeBo> sysUserDataScopeBoByRoleIds = sysRoleDataScopeService.getSysUserDataScopeBoByRoleIds(StringUtils.join(sysRoleIdSet, ","));
        sysUserDataScopeBoByRoleIds.stream().forEach(f->{
            if(  f.getCtrlType().equals("office")){
                Collections.addAll(officeSet, f.getCtrlDatas().split(","));
            }else if(f.getCtrlType().equals("user")){
                Collections.addAll(userSet, f.getCtrlDatas().split(","));
            }
        });
        //拥有部门权限
        if(null != userInfo.getOfficeId() && dataScopeSet.contains(2)){
            officeSet.add(userInfo.getOfficeId().toString());
        }
        Set<String> allOffices = new HashSet<>();
        allOffices.addAll(officeSet);
        if(officeSet.size() > 0){
            Set<String> allChildOfficeIds = officeMapper.findAllOfficeIds(officeSet);
            allOffices.addAll(allChildOfficeIds);
        }
        //获取所有权限部门的 子集部门
        if(null != userInfo.getUserId()){
            userSet.add(userInfo.getUserId().toString());
        }
        /** 查询所有部门下的用户  */
        if(allOffices.size() > 0){
            List<String> allOfficeUsers = baseMapper.listUserIdsByOfficIds(userInfo.getCompanyId(), StringUtils.join(allOffices, ","));
            userSet.addAll(allOfficeUsers);
        }
        dataScope.setOfficeIds(StringUtils.join(allOffices,","));
        dataScope.setUserIds(StringUtils.join(userSet,","));
        return dataScope;
    }

    @Override
    public SysUser checkUserEmail(SysUser user) {
        return userMapper.checkUserEmail(user);
    }

    @Override
    public HttpResult updateUser(SysUser user) {
        UserInfo userInfo = UserThreadLocal.get();
        if(user.getStatus() == 0) {
            List<UserInfo> userInfos = userMapper.getUserList(userInfo.getCompanyId());
            SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
            if(company.getCompanyUser() + company.getFreeUser() <= userInfos.size()) {
                throw new NuoNiuException("用户数不足，请购买或升级。");
            }
        }else {
            Integer roleId = 9;
            SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
            CrmGoods goods = crmGoodsService.getById(company.getGoodsId());
            if(goods != null) {
                roleId = goods.getRoleId();
            }

            SysUser sysUser = userMapper.getSysManager(userInfo.getCompanyId(), roleId);
            if(sysUser.getId() == user.getId()) {
                throw new NuoNiuException("不能停用系统管理员");
            }
        }
        this.updateById(user);
        return HttpResult.ok();
    }

    @Override
    public Page<SysUser> getShareUserList(Page page, SysUser user) {
        CrmWebConfig config = configService.getById(1);
        UserInfo userInfo = UserThreadLocal.get();
        if(config.getIsReward() && config.getFirstReward() > 0) {
            if(user.getShareUserId() == null) { //第一级
                user.setShareUserId(userInfo.getUserId());
            }else {
                Boolean flag = false;
                SysUser shareUser = this.getById(user.getShareUserId());
                if(StringUtils.isNotBlank(shareUser.getShareUserIds())) {
                    String[] ids = shareUser.getShareUserIds().split(",");
                    int k = 2;
                    for(int i=0; i < ids.length; i++) {
                        if(ids[i].equals(userInfo.getUserId().toString())) {
                            break;
                        }
                        k ++;
                    }
                    if(k == 2 && config.getSecondReward() > 0) { //第二级
                        flag = true;
                    }
                    if(k == 3 && config.getThirdReward() > 0) { //第三级
                        flag = true;
                    }
                    if(k == 4 && config.getFourthReward() > 0){ //第四级
                        flag = true;
                    }
                    if(!flag) {
                        user.setShareUserId(null);
                    }
                }
            }
        }


        Page<SysUser> pageUser = userMapper.getShareUserList(page, user);
        List<SysUser> userList = pageUser.getRecords();
        Integer month = Integer.valueOf(DateUtils.getMonth());
        Integer year = Integer.valueOf(DateUtils.getYear());
        CrmRetailLevel level = levelService.getById(1);
        for(SysUser sysUser : userList) {
           CrmUserLevel userLevel = userLevelService.getByUserId(sysUser.getId().intValue(), year, month);
           if(userLevel != null) {
               sysUser.setLevelName(userLevel.getName());
           } else {
               sysUser.setLevelName(level.getName());
           }
        }
        return pageUser;
    }

    @Override
    public Page<Map> getShareCrmList(Page page, SysCompany company) {
        UserInfo userInfo = UserThreadLocal.get();
        CrmWebConfig config = configService.getById(1);
        Integer index = 0;
        if(config.getIsReward() && config.getFirstReward() != null && config.getFirstReward() > 0) {
            company.setShareUserId(userInfo.getUserId());
            index = 1;
            if(config.getSecondReward() != null && config.getSecondReward() > 0) { //第二级
                index = 2;
            }
            if(config.getThirdReward() != null && config.getThirdReward() > 0) { //第三级
                index = 3;
            }
            if(config.getFourthReward() != null && config.getFourthReward() > 0){ //第四级
                index = 4;
            }
        }
        return userMapper.getShareCrmList(page, company, index);
    }

    @Override
    public HttpResult resetPwd(Map<String, String> userInfo) {
        String userPhone = userInfo.get("userPhone");
        String smsCode = redisService.get("sms_" + userPhone).toString();
        if(!smsCode.equals(userInfo.get("vCode"))) {
            throw new NuoNiuException("验证码不正确");
        }

        SysUser user = userMapper.findByUserName(userPhone);
        if(user == null) {
            throw new NuoNiuException("手机号未注册");
        }

        user.setPassword(bCryptPasswordEncoder.encode(userInfo.get("password")));
        userMapper.updateById(user);
        return HttpResult.ok();
    }

    @Override
    public HttpResult entryRegister(Map<String, String> registerUser) {
        String userPhone = registerUser.get("userPhone");
        String email = registerUser.get("email");
        Object smsCode = redisService.get("sms_" + userPhone);
        if(smsCode == null || !registerUser.get("vCode").equals(smsCode.toString())) {
            throw new NuoNiuException("验证码不正确");
        }

        SysUser sysUser = userMapper.findByEmail(email);
        if(sysUser != null && !(sysUser.getUserName().equals(userPhone))) {
            throw new NuoNiuException("邮箱已注册");
        }

        if(redisService.hasKey("register_" + userPhone)) {
            throw new NuoNiuException("正在注册中...");
        }

        redisService.set("register_" + userPhone, "用户注册", 5);
        List<UserInfo> userInfos = userMapper.getUserList(Integer.parseInt(registerUser.get("companyId")));
        SysCompany company = companyMapper.selectById(Integer.parseInt(registerUser.get("companyId")));
        //保存用户信息
        SysUser user = userMapper.findByUserName(userPhone);
        if(user != null) {
            user.setCompanyId(Integer.parseInt(registerUser.get("companyId")));
            user.setCompanyName(registerUser.get("companyName"));
            if(company.getCompanyUser() + company.getFreeUser() <= userInfos.size()) {
                user.setStatus(2);
            }
            userMapper.updateById(user);
            return HttpResult.ok();
        }else {
            user = new SysUser();
            user.setUserCode(com.nuoniu.sibanyun.common.lang.StringUtils.getRandomStr(6));
            user.setPassword(bCryptPasswordEncoder.encode(registerUser.get("password")));
            user.setMobile(userPhone);
            user.setUserName(userPhone);
            user.setRealName(registerUser.get("realName"));
            user.setEmail(email);
            user.setCompanyId(Integer.parseInt(registerUser.get("companyId")));
            user.setCompanyName(registerUser.get("companyName"));
            user.setTotalCommission(new BigDecimal(0));
            user.setWithdrawalCommission(new BigDecimal(0));
            user.setRegisterAddress(userLocation());
            if(company.getCompanyUser() + company.getFreeUser() <= userInfos.size()) {
                user.setStatus(2);
            }
            user.setId(user.getId());
            //user.setUpdateBy(user.getId().intValue());
            //user.setCreateBy(user.getId().intValue());
            SysOffice office = officeMapper.getOfficeName(company.getCompanyName(), company.getId());
            user.setOfficeId(office.getId());
            user.setOfficeCode(office.getOfficeCode());
            user.setOfficeName(company.getCompanyName());

            userMapper.insert(user);
            return HttpResult.ok();
        }


    }

    @Override
    public void updateCompanyName(SysCompany company) {
        userMapper.updateCompanyName(company);
    }

    @Override
    public HashMap<String,Object> getDataScopeUsers() {
        HashMap<String,Object> map = new HashMap<>();
        UserInfo userInfo = UserThreadLocal.get();
        DataScope dataScope = userInfo.getDataScope();
        String officeIds = dataScope.getOfficeIds();
        String userIds = dataScope.getUserIds();
        String[] officeIdsArr = officeIds.split(",");
        List<String> officeList = Arrays.asList(officeIdsArr);
        String[] userIdsArr = userIds.split(",");

        List<OfficeUserVo> dataScopeOfficeUsers;
        List<OfficeTreeData> officeData = new ArrayList<>();
        if(3 == dataScope.getType()){
            dataScopeOfficeUsers = baseMapper.getAllCompanyUsers(userInfo.getCompanyId());
            officeData = officeMapper.findAllOfficesByCompanyId(userInfo.getCompanyId());
        }else{
           dataScopeOfficeUsers = baseMapper.getDataScopeOfficeUsers(officeList, Arrays.asList(userIdsArr));
           if(officeList.size() > 0){
               officeData = officeMapper.findAllOffices(officeList);
           }
        }

        map.put("officeData",officeData);
        map.put("userData",dataScopeOfficeUsers);
        return map;
    }

    @Override
    public List<OfficeUserVo> getOfficeUserVo() {
        UserInfo userInfo = UserThreadLocal.get();
        DataScope dataScope = userInfo.getDataScope();
        String officeIds = dataScope.getOfficeIds();
        String userIds = dataScope.getUserIds();
        String[] officeIdsArr = officeIds.split(",");
        List<String> officeList = Arrays.asList(officeIdsArr);
        String[] userIdsArr = userIds.split(",");
        List<OfficeUserVo> dataScopeOfficeUsers;
        if(3 == dataScope.getType()){
            dataScopeOfficeUsers = baseMapper.getAllCompanyUsers(userInfo.getCompanyId());
        }else{
            dataScopeOfficeUsers = baseMapper.getDataScopeOfficeUsers(officeList, Arrays.asList(userIdsArr));
        }
        return dataScopeOfficeUsers;
    }

    @Override
    public List<Integer> getOfficeAllUserIds(Integer companyId,Integer officeId) {
        return baseMapper.getOfficeAllUserIds(companyId,officeId);
    }

    @Override
    public Page<SysUser> pageMember(Page page, SysUser user) {
        return userMapper.pageMember(page, user);
    }

    @Override
    public void updateUserType(UserInfo userInfo) {
        CrmWebConfig webConfig = configService.getById(1);
        SysUser user = userMapper.selectById(userInfo.getUserId());
        SysCompany sysCompany = new SysCompany();
        sysCompany.setCompanyCode(com.nuoniu.sibanyun.common.lang.StringUtils.getRandomStr(6));
        sysCompany.setCompanyName(userInfo.getCompanyName());
        sysCompany.setFullName(userInfo.getCompanyName());
        sysCompany.setRegisterIp(IpUtil.getClientIp(request));
        sysCompany.setFreeUser(webConfig.getFreeUsers());
        if(user.getShareUserId() != null) {
            sysCompany.setShareUserId(user.getShareUserId());
            sysCompany.setShareUserName(user.getShareUserName());
            sysCompany.setType("邀请码注册");
        }
        sysCompany.setRegisterAddress(userLocation());
        companyMapper.insert(sysCompany);

        //添加到诺牛科技客户下
        SysCompany company = companyMapper.selectById(88);
        if(company != null) {
            CrmCustomer crm = new CrmCustomer();
            crm.setCrmName(userInfo.getCompanyName());
            crm.setCrmType(0);
            crm.setCrmNo(crmCustomerService.getCustomerNo(88));
            crm.setCrmSource("注册");
            crm.setType("客户");
            crm.setCompanyId(88);
            crm.setCompanyName(company.getCompanyName());
            crm.setPhone(user.getUserName());
            crm.setEmail(user.getEmail());
            crmCustomerService.save(crm);
            //添加联系人
            CrmLinkman linkman = new CrmLinkman();
            linkman.setCrmId(crm.getId().intValue());
            linkman.setCrmName(crm.getCrmName());
            linkman.setName(user.getRealName());
            linkman.setMobile(user.getUserName());
            linkman.setEmail(user.getEmail());
            linkmanService.save(linkman);
        }

        //增加默认部门
        SysOffice office = new SysOffice();
        office.setCompanyId(sysCompany.getId().intValue());
        office.setCompanyName(userInfo.getCompanyName());
        office.setParentId(0);
        office.setParentIds("0,");
        office.setTreeNames(userInfo.getCompanyName());
        office.setOfficeName(userInfo.getCompanyName());
        office.setFullName(userInfo.getCompanyName());
        office.setOfficeType(1);
        office.setTreeSort(0);
        officeMapper.insert(office);
        //保存用户
        user.setCompanyId(sysCompany.getId().intValue());
        user.setCompanyName(sysCompany.getCompanyName());
        user.setId(user.getId());
        user.setRealName(user.getRealName());
        user.setOfficeName(userInfo.getCompanyName());
        user.setOfficeId(office.getId());
        //user.setUpdateBy(user.getId().intValue());
        //user.setCreateBy(user.getId().intValue());
//        baseMapper.insert(user);
        updateById(user);

        //默认管理员角色
        userRoleMapper.deleteByUserId(user.getId());
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(2L);
        userRole.setUserId(user.getId());
        userRoleMapper.insert(userRole);
        //异步copy系统字段、系统设置、客户设置
        saveCrmSysField(sysCompany.getId(), sysCompany.getCompanyName(), user.getId(), user.getRealName());
    }

    @Async
    public void saveUserLog(ProceedingJoinPoint joinPoint, Object res, long time, HttpServletRequest request) {}

    @Override
    public void smsRegister(Integer empId, String vCode) {
        SysUser user = baseMapper.selectById(empId);
        if(user != null && user.getId() == null && StringUtils.isNotBlank(user.getMobile())) {
            Object smsCode = redisService.get("sms_" + user.getMobile());
            if(smsCode == null || !vCode.equals(smsCode.toString())) {
                throw new NuoNiuException("验证码不正确");
            }

            SysCompany company = companyMapper.selectById(user.getCompanyId());
            List<UserInfo> userInfos = userMapper.getUserList(company.getId().intValue());
            user.setUserCode(com.nuoniu.sibanyun.common.lang.StringUtils.getRandomStr(6));
            user.setPassword(bCryptPasswordEncoder.encode("123456"));
            user.setTotalCommission(new BigDecimal(0));
            user.setWithdrawalCommission(new BigDecimal(0));
            user.setRegisterAddress(userLocation());
            if(company.getCompanyUser() + company.getFreeUser() <= userInfos.size()) {
                user.setStatus(2);
            }

            //添加新用户
            userMapper.insert(user);
            user.setId(user.getId());
        }
    }

    @Override
    public Page<SysUserDto> getPageList(SysUserDto userDto) {
        UserInfo userInfo = UserThreadLocal.get();
        userDto.setCompanyId(userInfo.getCompanyId().longValue());
        return baseMapper.getPageList(userDto.getPage(), userDto);
    }

    @Override
    public SysUser getByRealName(String realName) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        wrapper.eq("real_name", realName);
        wrapper.last("LIMIT 1");
        return this.getOne(wrapper);
    }

    @Override
    public SysUser getUserAdmin(Integer companyId) {
        SysCompany company = companyMapper.selectById(companyId);
        if(!company.getId().equals(1) && company.getGoodsId() != null) {
            CrmGoods goods = crmGoodsService.getById(company.getGoodsId());
            return userMapper.getSysManager(companyId, goods.getRoleId());
        }
        return null;
    }

    @Override
    public MenuVo getByMenuPermission(Integer companyId, String permission) {
        MenuVo vo = new MenuVo();
        SysMenu menu = sysMenuService.getByMenuPermission(permission);
        if(menu != null) {
            vo.setUserInfoList(baseMapper.getByMenuPermissionList(companyId, menu.getId()));
            vo.setMenu(sysMenuService.getById(menu.getParentId()));
            return vo;
        } else {
            return null;
        }
    }

    @Override
    public List<SysUser> getShareUserAll() {
        UserInfo userInfo = UserThreadLocal.get();
        List<SysUser> userList = baseMapper.getShareUserAll(userInfo.getUserId());
        Integer year = Integer.valueOf(DateUtils.getYear());
        Integer month = Integer.valueOf(DateUtils.getMonth());
        if(month == 1) {
            month = 12;
            year = year -1;
        }

        CrmRetailLevel level = levelService.getById(1);
        for(SysUser user : userList) {
            CrmUserLevel userLevel = userLevelService.getByUserId(user.getId().intValue(), year, month);
            if(userLevel != null) {
                user.setLevelName(userLevel.getName());
            } else {
                user.setLevelName(level.getName());
            }
        }
        return userList;
    }

    @Override
    public void updateCompanyType() {
        UserInfo userInfo = UserThreadLocal.get();
        SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
        if(company == null) {
            throw new NuoNiuException("已是个人身份");
        }

        if(!company.getId().equals(1)) {
            QueryWrapper wrapper = new QueryWrapper();
            Integer roleId = 2 ;
            wrapper.eq("company_id", userInfo.getCompanyId());
            Integer count  = this.count(wrapper);
            if(company.getGoodsId() != null) {
                CrmGoods goods = crmGoodsService.getById(company.getGoodsId());
                if(goods != null && goods.getRoleId() != null) {
                    roleId = goods.getRoleId();
                }
            }

            SysUser user = userMapper.getSysManager(userInfo.getCompanyId(), roleId);
            if (user != null && user.getId().equals(userInfo.getUserId().longValue())) {
                if(count > 1) {
                    throw new NuoNiuException("你当前身份为系统管理员并且员工数大于0，请到“系统管理->用户管理->更换管理员”");
                }
            } else {
                throw new NuoNiuException("您没有此权限，员工请点击离职");
            }

            //删除此机构所有数据
            if(count == 1) {
                List<SysRdtForm> formList = formMapper.getFromList();
                for(SysRdtForm form : formList) {
                    if(form.getFormNameEn().equals("sys_user")) {
                        continue;
                    }

                    try {
                        System.out.println("删除表=====" + form.getFormNameEn());
                        baseMapper.deleteFormCompany(form.getFormNameEn(), userInfo.getCompanyId());
                    } catch (Exception e) {
                        continue;
                    }

                    //删除机构
                    companyMapper.deleteById(company.getId());
                }
            }

            //清理用户权限
            userRoleMapper.deleteByUserId(userInfo.getUserId().longValue());
            //删除机构信息
            baseMapper.deleteCompany(userInfo.getUserId());
            //删除员工信息
            baseMapper.deleteByUserId(userInfo.getUserId());
        }
    }

    @Override
    public void quit(Integer userId) {
        UserInfo userInfo = UserThreadLocal.get();
        userId = userId == null ? userInfo.getUserId() : userId;
        Integer rold = 2;
        SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
        if(company == null) {
            throw new NuoNiuException("个人用户不能离职");
        }

        if(!company.getId().equals(1)) {
            if (company.getGoodsId() != null) {
                CrmGoods goods = crmGoodsService.getById(company.getGoodsId());
                if(goods != null && goods.getRoleId() != null) {
                    rold = goods.getRoleId();
                }
            }

            SysUser user = userMapper.getSysManager(userInfo.getCompanyId(), rold);
            if (user != null && user.getId().equals(userId.longValue())) {
                throw new NuoNiuException("你当前身份为系统管理员，请到“个人中心->设置->账户信息”变更用户类型 ");
            }

            Integer crmCount = crmMapper.getUserCount(userId);
            if(crmCount > 0) {
                throw new NuoNiuException("该用户下有领用客户，请前往分配给其他人");
            }

            //删除权限
            userRoleMapper.deleteByUserId(userId.longValue());
            //删除机构信息
            baseMapper.deleteCompany(userId);
            //删除员工信息
            baseMapper.deleteByUserId(userId);
        }
    }


    /**
     * 设置参数
     */
    public String getMapToParams(Map<String, String[]> paramMap) {
        StringBuilder params = new StringBuilder();
        for (Map.Entry<String, String[]> param : ((Map<String, String[]>)paramMap).entrySet()){
            params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
            String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
            params.append(paramValue) ;
        }
        return params.toString();
    }

    public void updateLoginInfo(Long id) {
        SysUser user = userMapper.selectById(id);
        SysUser updateUser = new SysUser();
        updateUser.setId(id);
        updateUser.setLoginCount(user.getLoginCount() + 1);
        updateUser.setLastLoginDate(LocalDateTime.now());
        updateUser.setLastLoginIp(IpUtil.getClientIp(request));
        updateById(updateUser);
        SysCompany company = companyMapper.selectById(user.getCompanyId());
        SysCompany updateSysCompany = new SysCompany();
        if(company != null) {
            updateSysCompany.setId(company.getId());
            updateSysCompany.setLoginDate(LocalDateTime.now());
            updateSysCompany.setLoginIp(IpUtil.getClientIp(request));
            updateSysCompany.setLoginCount(company.getLoginCount() + 1);
            companyMapper.updateById(updateSysCompany);
        }
    }

    /**
     * 用户定位
     * @author 小啊刚
     * @date 2019/7/24
     */
    public String  userLocation() {
        String ip = IpUtil.getClientIp(request);
        String json = HttpClientUtil.sendGet("http://restapi.amap.com/v3/ip?ip=" + ip + "&output=json&key=301f337573ecffc06cfffd47b096416f");
        Map location = JSONObject.parseObject(json);
        return location.get("city").toString();
    }

    public static void main(String[] args) {
    }



}
